<?php

namespace App\Http\Controllers\Setting\Template;

use App\Http\Controllers\Controller;
use App\Models\Common\Wechat;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TemplateSendController extends Controller
{

    public function index()
    {
        $all = $this->all;
        $openid = $all['openid'];
        $path = $all['path'];
        $template = $all['template'];
        $receive_data = $all['data'];


        if (env('APP_ENV') === 'local') return $this->setReturnJson(-1,'本地无法推送');

        try{

            // openid:根据空格拆分成数组
            $openid = explode(' ', $openid);

            // data
            $template_data = Data::$wechat_blade_detail[$template];
            $data = [];
            foreach ($template_data as $key => $value) {
                $data[$key] = $receive_data[$key] ?? '';
            }

            // 统计推送成功数量
            $total = count($openid);
            $success = 0;
            $failed = 0;

            $insert_array = [];

            $app = Wechat::officialAccount();
            foreach ($openid as $id) {
                try {
                    $result = $app->template_message->send([
                        "touser" => $id,
                        "template_id" => Data::$wechat_blade[env('APP_ENV')][$template],
                        "url" => $path,
                        "data" => $data,
                    ]);
                    if ($result['errcode'] === 0) {
                        $success++;
                        $insert_array[] = [
                            'openid' => $id,
                            'success' => 1,
                        ];
                    } else {
                        $failed++;
                        $insert_array[] = [
                            'openid' => $id,
                            'success' => 0,
                        ];
                        Log::info('公众号通知推送失败', $result);
                    }
                } catch (\Exception $e) {
                    Log::error(TemplateSendController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
                }
            }

            // 记录日志
            $send_user = $this->userInfo['id'];
            $data = json_encode($data);
            foreach($insert_array as &$insert){
                $insert['blade_name'] = $template;
                $insert['method'] = 'TemplateSendController';
                $insert['data'] = $data;
                $insert['path'] = $path;
                $insert['send_user'] = $send_user;
            }
            DB::table('sys_template_log')->insert($insert_array);

            return $this->setReturnJson(0, '本次推送总计：' . $total . '个，推送成功：' . $success . '个，推送失败：' . $failed . '个，详情请查看推送历史记录');
        }catch (\Exception $e){
            Log::error(TemplateSendController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'发送失败',['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }

    }

}
